package com.cats.bi.sqltool.syntax.sort;

import com.cats.bi.sqltool.SQLString;
import com.cats.bi.sqltool.basic.AbstractColumn;
import com.cats.bi.sqltool.basic.Column;
import lombok.val;

import java.util.LinkedHashMap;
import java.util.Map.Entry;
import java.util.Set;

/**
 * @author wang
 */
public abstract class AbstractSort implements SQLString {

    static final String ASC = "ASC";
    static final String DESC = "DESC";

    private LinkedHashMap<Object, String> sort = new LinkedHashMap<>();

    AbstractSort(AbstractColumn<?> column, String sortType) {
        sort.put(column, sortType);
    }

    AbstractSort(String column, String sortType) {
        this.sort.put(column, sortType);
    }

    public AbstractSort asc(Column column) {
        sort.put(column, ASC);
        return this;
    }

    public AbstractSort desc(Column column) {
        sort.put(column, DESC);
        return this;
    }

    public AbstractSort asc(String column) {
        sort.put(column, ASC);
        return this;
    }

    public AbstractSort desc(String column) {
        sort.put(column, DESC);
        return this;
    }

    @Override
    public void toSql(StringBuilder sql) {
        if (sort.size() == 0) {
            return;
        }
        sql.append(" ORDER BY ");
        boolean f = true;
        Set<Entry<Object, String>> set = sort.entrySet();
        for (Entry<Object, String> cell : set) {
            if (f) {
                f = false;
            } else {
                sql.append(", ");
            }
            Object column = cell.getKey();
            if (!(column instanceof AbstractColumn)) {
                SQLString.appendColumn(sql, column.toString());
            } else {
                val c = (AbstractColumn) column;
                c.shortName(sql);
            }
            String sc = cell.getValue();
            if (sc != null) {
                sql.append(" ");
                sql.append(sc);
            }
        }
    }

    public static class Asc extends AbstractSort {
        public Asc(Column column) {
            super(column, ASC);
        }

        public Asc(String column) {
            super(column, ASC);
        }
    }
}
